#!/usr/bin/env python3
from epics import PV, caget
import time
import datetime


class Watchdog(object):
    """Watchdog channel status
       triggered by LLRF
    """

    @property
    def value_now(self):
        return self.pv.get()

    def on_value_change(self, pvname=None, value=None,
                        conn=None, host=None, timestamp=None, **kwargs):
        if self.init_status:
            self.pre_value = self.value
            self.value = value
            if self.pre_value != self.value:
                self.timeout_reset
            self.timestamp = timestamp
            self.callback_function()
            if conn is False:
                info_str = ('ca connection status changed:  %s %s %s'
                            % (pvname, conn, host))
                self.error_raise(info_str)
            else:
                pass
        else:
            pass

    def error_raise(self, info_str):
        if self.logging is None:
            print(info_str)
        else:
            self.logging.info(info_str)

    @property
    def time_now(self):
        return datetime.datetime.strftime(datetime.datetime.now(),
                                          '%Y-%m-%d %H:%M:%S.%f')

    @property
    def count_down(self):
        """Count down timeout value"""
        while True:
            if self.timeout == 0:
                info_str = ('%s %s seconds timeout at %s.'
                            % (self.pvname, self.timeout_init, self.time_now))
                self.error_raise(info_str)
                break
            else:
                info_str = ('%s %s count down at %s.'
                            % (self.pvname, self.timeout, self.time_now))
                self.error_raise(info_str)
                self.timeout -= 1
                time.sleep(1)
        self.callback_function()

    def callback_function(self):
        if callable(self.callback):
            self.callback(self)
        else:
            pass

    @property
    def timeout_reset(self):
        self.timeout = self.timeout_init

    def __init__(self, watchdog_dict, timeout, callback=None,
                 logging=None):
        self.init_status = False
        self.logging = logging
        self.watchdog_name = watchdog_dict['watchdog_name'][1]
        self.callback = callback
        self.timeout_init = timeout
        self.timeout = timeout
        self.pvname = watchdog_dict['pvname'][1]
        caget(self.pvname)
        self.pv = PV(self.pvname, callback=self.on_value_change)
        self.value = self.value_now
        self.pre_value = self.value_now
        self.timestamp = None
        self.init_status = True
        self.count_down

    def __del__(self):
        print('Delete watchdog.watchdog instance -> '
              + self.watchdog_name + ' -> ' + self.pvname)


def main():
    pass


if __name__ == '__main__':
    main()
